package com.admin.controller;

import java.io.File;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;

import com.admin.interceptor.LoginInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;

@Before(LoginInterceptor.class)
public class BaseController extends Controller{
	public Log logger = LogFactory.getLog(BaseController.class);
	
	// 操作状态(警告，成功，错误)
	public enum Status{
		warn,success,error,success1
	}
	
	/**
	 * 更改文件名,重新得到文件路径
	 * @param file
	 * @return
	 */
	public String getUploadFile(File file){
		String fileType = "";
		String fileName = file.getName();
		int point = fileName.lastIndexOf(".");
		if(point != -1){
			fileType = fileName.substring(point);
		}
		if(file.length() <= 2097152){
			String time = String.valueOf(new Date().getTime());
			String saveFileName = time + (int)(Math.random()*100)+fileType;
			return PathKit.getWebRootPath()+File.separator+"upload"+File.separator+saveFileName;
		}else{
			return null;
		}
	}
	
	/**
	 * 封装json数据
	 * @param status
	 * @param msg
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject ajax(Status status,String msg){
		JSONObject json = new JSONObject();
		json.put("status",status);
		json.put("msg",msg);
		return json;
	}
	
	/**
	 * 异步返回提示页面
	 * @param status
	 */
	public void ajax(Status status,String tabId,Boolean closeCurrent){
		if(status == Status.success){
			setAttr("tabId",tabId);
			setAttr("closeCurrent",closeCurrent);
			renderJsp("/jsp/message/ajaxSuccess.jsp");
		}else if(status == Status.error){
			renderJsp("/jsp/message/ajaxError.jsp");
		}else{
			renderJsp("/jsp/404.jsp");
		}
	}
}
